package com.lxj.service.impl;

import com.lxj.common.CodeMsg;
import com.lxj.common.Result;
import com.lxj.domain.SysPermission;
import com.lxj.dto.SysPermissionDto;
import com.lxj.mapper.SysPermissionMapper;
import com.lxj.service.PermissionService;
import com.lxj.vo.PageInfo;
import com.lxj.vo.TreeNode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lxj
 * @date 2021/6/18 18:21
 * @Description:权限的业务
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private SysPermissionMapper mapper;

    /**
     * 查询所有的树菜单
     * @return
     */
    @Override
    public List<SysPermission> selectAllSysPermission() {
        return mapper.selectAll();
    }

    /**
     * 将一个普通的权限集合转化为一棵树
     * @param allData
     * @return
     */
    @Override
    public List<TreeNode> convertTreeNode(List<SysPermission> allData) {
        return convertTreeNodeInner(allData);
    }

    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public List<SysPermission> findByPage(SysPermissionDto dto) {
        return mapper.selectByPage(dto);
    }

    /**
     * 新增权限
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result addPermission(SysPermissionDto dto) {
        //数据校验
        if (dto.getParentId() == null) {
            return new Result(CodeMsg.PERMISSION_PARENT_ID_IS_NULL);
        }
        if (dto.getTitle() == null) {
            return new Result(CodeMsg.PERMISSION_TYPE_IS_NULL);
        }
        // 我必须是目录
        if (dto.getParentId() == 0) {
            if (dto.getType() != 0) {
                return new Result(CodeMsg.PERMISSION_ROOT_IS_NOT_LIST);
            }
        }
        // 菜单必须有href
        if (dto.getType() == 1) {
            if (dto.getHref() == null) {
                return new Result();
            }
        }
        // 按钮必须有权限的标识
        if (dto.getType() == 2) {
            if (dto.getTag() == null) {
                return new Result(CodeMsg.PERMISSION_BUTTON_IS_NOT_TAG);
            }
        }
        SysPermission sysPermission = new SysPermission();
        BeanUtils.copyProperties(dto,sysPermission);
        sysPermission.setSpread(dto.getSpread() == 1 ? true : false);
        mapper.insert(sysPermission);
        return new Result();
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Result batchDelete(Integer[] ids) {
        for (Integer id : ids) {
            Integer count = mapper.selectCountByParentId(id);
            if(count != null && count > 0 ){
                return new Result(CodeMsg.PERMISSION_CHILDREN_NOT_NULL);
            }
            mapper.deleteByPrimaryKey(id);
        }
        return new Result();
    }

    /**
     * 修改权限
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result updatePermission(SysPermissionDto dto) {
        SysPermission sysPermission = new SysPermission();
        BeanUtils.copyProperties(dto,sysPermission);
        sysPermission.setSpread(dto.getSpread() == 1 ? true : false);
        mapper.updateByPrimaryKey(sysPermission);
        return new Result();
    }

    /**
     * 获取当前角色的权限的id 集合
     * @param roleId 角色的id
     * @return
     */
    @Override
    public List<Integer> getPermsByRoleId(Integer roleId) {
        return mapper.selectPermIdByRoleId(roleId);
    }

    /**
     * 给角色分配权限
     * @param roleId
     * @param permsIds
     * @return
     */
    @Override
    @Transactional
    public void assign(Integer roleId, Integer[] permsIds) {
        //删除旧值
        mapper.deleteByRoleIds(roleId);
        //创建新值
        mapper.insertNewRole(roleId, permsIds);
    }
    /**
     * 查询特定类型的权限
     * @param id 用户的id
     * @param types 类型的集合
     * @return
     */
    @Override
    public List<SysPermission> getPermsByUserIdAndType(Integer id, List<Integer> types) {
        return mapper.selectPermsByUserIdAndType(id, types);
    }

    private List<TreeNode> convertTreeNodeInner(List<SysPermission> allData) {
        Map<Integer, TreeNode> treeMap = new HashMap<>();
        for (SysPermission allDatum : allData) {
            TreeNode treeNode = new TreeNode();
            //将数据库查询的数据拷贝到treeNode
            BeanUtils.copyProperties(allDatum,treeNode);
            //如果权限类型为1（菜单类型）则添加属性_iframe
            treeNode.setOpenType(treeNode.getType() == 1 ? "_iframe" : "");
            //将数据库的数据全部放入map集合
            treeMap.put(allDatum.getId(), treeNode);
        }
        List<TreeNode> roots = new ArrayList<>();
        // 使用父亲的id 给父亲添加元素
        treeMap.forEach((id,node) ->{
            // 获取父亲的id
            Integer parentId = node.getParentId();
            // 获取父亲的节点
            TreeNode treeNode = treeMap.get(parentId);
            if(treeNode != null){
                treeNode.getChildren().add(node);
            }else {
                roots.add(node);
            }
        });
        return roots;
    }

}
